package com.ww.springboot.boot.thread.study.executor;

import java.util.concurrent.*;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-04-01 08:54
 */
public class Executor拒绝策略 {

    private static final ExecutorService executorService = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2));
    private static final ExecutorService executorService2 = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());


    /**
     * 线程池任务被拒绝 会抛出异常,捕获异常后补偿任务(补偿任务使用linkBlockingQueue 因为补偿任务肯定是占少部分的,所以使用无界阻塞队列更合适 避免任务再次被丢弃)即可
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            try {
                executorService.submit(() -> {
                    System.out.println(Thread.currentThread() + "---开始");
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread() + "---结束");
                });
            } catch (RejectedExecutionException e) {
                e.printStackTrace();
                System.out.println(i + "任务被拒绝---");
                executorService2.submit(() -> {
                    System.out.println(Thread.currentThread() + "---开始");
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e2) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread() + "---结束");
                });
            }

        }
    }
}
